package org.javaboy.sms_login.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

public class SmsAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //判断一下是手机验证码登录还是用户名密码登录
        String phone = request.getParameter("phone");
        if (phone != null && !"".equals(phone)) {
            //说明登录参数中有手机号码，认为是手机验证码登录
            SmsAuthenticationToken authRequest = SmsAuthenticationToken.unauthenticated(request.getParameter("phone"),
                    request.getParameter("code"));
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        return super.attemptAuthentication(request, response);
    }
}
